<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>匹配验证码</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        span{
            display: inline-block;
            width: 100px;
            height: 20px;
            background: #58bc58;
            border: 1px solid #000;
            text-align: center;
            /* 禁止选中文字 */
            user-select: none;
        }
        div{
            display: flex;
            margin: 50px auto;
            width: 900px;
        }
        button{
            margin-left: 10px;
            width: 50px;
        }
    </style>
</head>
<body>
    <div>
        <label for="">验证码：</label><input id='code' type="text">
        <span></span>
        <button>提交</button>
    </div>

    <script>
        var span = document.getElementsByTagName('span')[0];
        var btn = document.getElementsByTagName('button')[0];
        var input = document.getElementById('code');

        /* 
            封装随机生成4位数字

                * 自己：四位数拼接
                * 课堂：1000-9999随机生成【比较推荐】
         */
        function newCode(){
            var code = '';
            for(var i=0;i<4;i++){
                code += parseInt(Math.random()*10);
            }
            return code;
        }
        
        // 初始化
        span.innerHTML = newCode();
        
        // 点击重新生成验证码
        span.onclick = function(){
            span.innerHTML = newCode();
        }

        // 验证匹配
        btn.onclick = function(){
            var nowCode = span.innerHTML*1;
            var inputNumber = input.value*1;
            // console.log(nowCode,inputNumber);
            if(nowCode==inputNumber){
                alert('验证成功');
            }else{
                alert('请重新验证');
                newCode();
                input.value = '';
            }
        }
    </script>
</body>
</html>